// MarketInternalGoodsCodeManager.tsx
import React, {useState, useEffect, useCallback, CSSProperties, useMemo} from 'react';
import {Table, Button, Input, Space, Form, Popconfirm, message} from 'antd';
import type {ColumnsType} from 'antd/es/table';
import GoodsWithSubGoodsSelector from './GoodsWithSubGoodsSelector';
import {
    getAllInternalGoodsCodes,
    addInternalGoodsCode,
    updateInternalGoodsCode,
    deleteInternalGoodsCode,
    MarketInternalGoodsCodeResponse
} from '../apis/MarketInternalGoodsCodeApi';
import DataPageLayout from "./DataPageLayout";
import {observer} from 'mobx-react';
import employeeAuthorizationStore from "../store/EmployeeAuthorizationStore";

interface MarketInternalGoodsCodeManagerProps {
    marketId: number;
    style?: CSSProperties
}

const MarketInternalGoodsCodeManager: React.FC<MarketInternalGoodsCodeManagerProps> = ({marketId, style}) => {
    const [internalCodes, setInternalCodes] = useState<MarketInternalGoodsCodeResponse[]>([]);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const [editingId, setEditingId] = useState<number | null>(null);
    const [newCode, setNewCode] = useState('');
    const [selectedGoods, setSelectedGoods] = useState<any[]>([]);

    // 加载内部码数据
    const loadInternalCodes = useCallback(async () => {
        setLoading(true);
        try {
            const response = await getAllInternalGoodsCodes(marketId);
            setInternalCodes(response.data);
        } catch (error) {
            message.error('加载内部码失败');
        } finally {
            setLoading(false);
        }
    }, [marketId]);

    useEffect(() => {
        loadInternalCodes();
    }, [loadInternalCodes]);

    // 添加新内部码
    const handleAdd = async () => {
        if (!newCode.trim() || selectedGoods.length === 0) {
            message.warning('请填写内部码并选择商品');
            return;
        }

        try {
            const goodsId = selectedGoods[0].id;
            await addInternalGoodsCode(marketId, {
                code: newCode,
                goodsId
            });

            message.success('添加成功');
            setNewCode('');
            setSelectedGoods([]);
            loadInternalCodes();
        } catch (error) {
            message.error('添加失败');
        }
    };

    // 开始编辑
    const startEdit = (record: MarketInternalGoodsCodeResponse) => {
        setEditingId(record.id);
        form.setFieldsValue({code: record.code});
    };

    // 取消编辑
    const cancelEdit = () => {
        setEditingId(null);
    };

    // 保存编辑
    const saveEdit = async (id: number) => {
        try {
            const values = await form.validateFields();
            await updateInternalGoodsCode(marketId, id, {code: values.code});
            message.success('更新成功');
            setEditingId(null);
            loadInternalCodes();
        } catch (error) {
            message.error('更新失败');
        }
    };

    // 删除内部码
    const handleDelete = async (id: number) => {
        try {
            await deleteInternalGoodsCode(marketId, id);
            message.success('删除成功');
            loadInternalCodes();
        } catch (error) {
            message.error('删除失败');
        }
    };

    // 表格列定义
    const columns = useMemo(()=>{
        const columns: ColumnsType<MarketInternalGoodsCodeResponse> = [
            {
                title: '内部码',
                dataIndex: 'code',
                key: 'code',
                render: (text, record) => {
                    if (editingId === record.id) {
                        return (
                            <Form form={form} component={false}>
                                <Form.Item
                                    name="code"
                                    rules={[{required: true, message: '请输入内部码'}]}
                                    initialValue={text}
                                >
                                    <Input/>
                                </Form.Item>
                            </Form>
                        );
                    }
                    return text;
                },
            },
            {
                title: '商品',
                key: 'goods',
                render: (_, record) => (
                    <div>
                        <div>{record.name}</div>
                        <div style={{fontSize: 12, color: '#666'}}>条码: {record.barcode}</div>
                    </div>
                ),
            },

        ];
        if (employeeAuthorizationStore.hasAnyAuthority("卖场_内部码_删除","卖场_内部码_修改")){
            columns.push({
                title: '操作',
                key: 'action',
                width: 150,
                render: (_, record) => {
                    if (editingId === record.id) {
                        return (
                            <Space>
                                <Button type="link" size="small" onClick={() => saveEdit(record.id)}>
                                    保存
                                </Button>
                                <Button type="link" size="small" onClick={cancelEdit}>
                                    取消
                                </Button>
                            </Space>
                        );
                    }
                    return (
                        <Space>
                            {employeeAuthorizationStore.hasAuthority("卖场_内部码_修改") &&
                                <Button type="link" size="small" onClick={() => startEdit(record)}>
                                    编辑
                                </Button>}
                            {employeeAuthorizationStore.hasAuthority("卖场_内部码_删除") && <Popconfirm
                                title="确定要删除吗？"
                                onConfirm={() => handleDelete(record.id)}
                            >
                                <Button type="link" size="small" danger>
                                    删除
                                </Button>
                            </Popconfirm>}
                        </Space>
                    );
                },
            },)
        }
        return columns
    },[employeeAuthorizationStore.employee])


    return (
        <div style={style}>
            <DataPageLayout leftActions={employeeAuthorizationStore.hasAuthority("卖场_内部码_创建") ? <>
                <Input
                    placeholder="输入内部码"
                    value={newCode}
                    onChange={(e) => setNewCode(e.target.value)}
                    style={{width: 200}}
                />

                <GoodsWithSubGoodsSelector
                    style={{width: 300}}
                    mode={undefined} // 设置为单选模式
                    value={selectedGoods}
                    onChange={(items) => setSelectedGoods(items)}
                    placeholder="选择商品"
                />

                <Button type="primary" onClick={handleAdd}>
                    添加
                </Button>
            </> : <></>}>

                {/*内部码列表 */}
                <Table
                    columns={columns}
                    dataSource={internalCodes}
                    rowKey="id"
                    loading={loading}
                    pagination={false}
                    size="middle"
                />
            </DataPageLayout>
        </div>
    );
};

export default observer(MarketInternalGoodsCodeManager);